package com.example.springdemo03.controller;

import com.example.springdemo03.po.DataModel;
import com.example.springdemo03.service.DealDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Collectors;

@Controller
public class DealDataController {
    @Autowired
    private DealDataService dealDataService;

    @RequestMapping("/search")
    public ModelAndView index(@RequestParam(name = "key", required = false) String key){
        Stream<DataModel> dataModelStream = dealDataService.getData().parallelStream();
        List<DataModel> dataModelList;

        if (key == null){
            dataModelList=dataModelStream.sorted((data1, data2) -> -Integer.compare(data1.getLatestTotalCases(),
                    data2.getLatestTotalCases()))
                    .collect(Collectors.toList());
        }else{
            dataModelList=dataModelStream.filter(data -> data.getState().startsWith(key) ||
                    data.getCountry().startsWith(key))
                    .sorted((data1, data2) -> -Integer.compare(data1.getLatestTotalCases(),
                            data2.getLatestTotalCases()))
                    .collect(Collectors.toList());
        }
        System.out.println(dataModelList);
        return new ModelAndView("index","datalist",dataModelList);
    }
}
